/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author VANDH
 */
public class BinaryFile {

    public static void main(String[] args) throws IOException {
        String fileName = "D:\\binaryData.data";
        Scanner keyboard = new Scanner(System.in);
        int choice = 3;

        do {

            System.out.println("1. Write to file");
            System.out.println("2. Read from file");
            System.out.println("3. Exist");
            choice = keyboard.nextInt();

            switch (choice) {
                case 1:
                    writeToFile(fileName);
                    break;
                case 2:
                    readFromFile(fileName);
                    break;
            }
        } while (choice != 3);
    }

    private static void writeToFile(String fileName) {

        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));

            String studentName = "Nguyen Van A";
            int studentAge = 100;
            boolean female = false;

            dos.writeUTF(studentName);
            dos.writeInt(studentAge);
            dos.writeBoolean(female);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BinaryFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BinaryFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException ex) {
                    Logger.getLogger(BinaryFile.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }

    private static void readFromFile(String fileName) throws IOException {
        DataInputStream dis = null;

        try {
            dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));

            System.out.println(dis.readUTF());
            System.out.println(dis.readInt());
            System.out.println(dis.readBoolean());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (dis != null) {
                dis.close();
            }
        }
    }
}
